from datetime import datetime
from django.contrib import admin
from django.utils.safestring import mark_safe
from django.urls import reverse
from django.utils.html import format_html

from task.models import Task
from task.utils.rabbitmq_producer import publish_task_message

class TaskAdmin(admin.ModelAdmin):
    list_display = ['task_name', 'colored_status', 'download_img', 'download_xlsx', 'pub_date']
    list_display_links = None
    fields = ['task_name', 'file']
    search_fields = ['task_name']
    list_filter = ['pub_date']
    readonly_fields = ['pub_date', 'status', 'result_img_name', 'result_xlsx_name']

    def colored_status(self, obj):
        status_map = {
            -1: ("错误", "#dc3545"),
            0: ("未开始", "#6c757d"),
            1: ("进行中", "#fd7e14"),
            2: ("已完成", "#28a745"),
        }
        label, color = status_map.get(obj.status, ("未知", "black"))
        html = f'''
            <span style="
                display: inline-block;
                padding: 2px 8px;
                border-radius: 4px;
                background-color: {color};
                color: white;
                font-weight: bold;
            ">
                {label}
            </span>
        '''
        return mark_safe(html)

    colored_status.short_description = "任务状态"

    def download_img(self, obj):
        if obj.result_img_name:
            url = f"/media/downloads/{obj.id}/{obj.result_img_name}"  # 这里根据你的 MEDIA_URL 和文件保存路径修改
            return format_html(f'<a href="{url}" download>下载图片</a>')
        return "-"

    download_img.short_description = "图片结果"

    def download_xlsx(self, obj):
        if obj.result_xlsx_name:
            url = f"/media/downloads/{obj.id}/{obj.result_xlsx_name}"
            return format_html(f'<a href="{url}" download>下载表格</a>')
        return "-"

    download_xlsx.short_description = "表格结果"

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(user=request.user)

    def formfield_for_dbfield(self, db_field, **kwargs):
        formfield = super().formfield_for_dbfield(db_field, **kwargs)
        if db_field.name == 'file':
            formfield.widget.attrs.update({'accept': '.zip, .rar, .7z'})
        return formfield

    def save_model(self, request, obj, form, change):
        is_new = not obj.pk
        if is_new:
            obj.user = request.user
            obj.pub_date = datetime.now()
            obj.status = 0
            obj.result_img_name = ''
            obj.result_xlsx_name = ''
        super().save_model(request, obj, form, change)

        if is_new and obj.file:
            publish_task_message(
                task_id=obj.id,
                task_name=obj.task_name,
                file_name=obj.file.name
            )

admin.site.register(Task, TaskAdmin)
